package com.digitalchina.lxnsy.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.ShareFarmManagerActivity;
import com.digitalchina.lxnsy.api.BusinessShareFarm;
import com.digitalchina.lxnsy.base.BaseFragment;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ShareFarmListVO;
import com.digitalchina.lxnsy.interfaces.ICallBackActivity;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.ShareFarmSellHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/10/19 10:51
 * 修改备注：
 * ================================================
 */
public class ShareSellFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, ICallBackActivity {

    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;
    private List<ShareFarmListVO> voList = new ArrayList<>();

    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_share_sell);
    }

    @Override
    public void initMember() {

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.addItemDecoration(Utils.setSpaceDecoration(getActivity(), false, true, false));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(getActivity()) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new ShareFarmSellHolder(parent, ShareSellFragment.this);
            }
        });

        onRefresh();
    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
//                GotoUtil.gotoActivity(getActivity(), ActivityDetailActivity.class, "ActivityVO", adapter.getAllData().get(position));
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (getActivity().isFinishing())
                    return;

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_GET_USER_SHARE_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_USER_SHARE_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_OFFLINE_AGRICULTURE_PRODUCT_SUCCESS:
                        showToast("下架成功");
                        onRefresh();
                        if (getActivity() != null)
                            ((ShareFarmManagerActivity) getActivity()).onRefreshList(2);
                        break;
                    case MSG.MSG_OFFLINE_AGRICULTURE_PRODUCT_FIELD:
                        showToast(msg.obj.toString());
                        break;

                }
            }
        };
    }

    @Override
    public void callBack(final Object object) {


        new Thread(new Runnable() {
            @Override
            public void run() {

                voList = FastJsonUtil.getListBean(object.toString(), "list", ShareFarmListVO.class);

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (page == 1) { // 刷新
                            adapter.clear();
                        }


                        adapter.addAll(voList);

                        if (voList != null) {
                            if (voList.size() < limit) {
                                adapter.stopMore();
                            }
                        }
                    }
                });
            }
        }).start();


    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessShareFarm.getUserShare(getActivity(), "1", page, limit, mHandler);
    }

    @Override
    public void manage(int position) {
    }

    @Override
    public void edit(int position) {
    }

    @Override
    public void cancel(final int position) {
        // 下架
        new MaterialDialog.Builder(getActivity())
                .title("提示")
                .content("确定下架该商品？")
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        ShareFarmListVO vo = (ShareFarmListVO) adapter.getAllData().get(position);
                        BusinessShareFarm.offlineAgricultureProduct(getActivity(), vo.getId(), mHandler);
                    }
                })
                .show();
    }

    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= limit) {
            page++;
            BusinessShareFarm.getUserShare(getActivity(), "1", page, limit, mHandler);
        }
    }
}
